<?php

namespace addons\shopro\controller\user;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\Config;
use app\common\library\Sms;
use addons\shopro\controller\Common;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
use app\admin\model\shopro\ThirdOauth;
use fast\Http;
use think\Db;

class User extends Common
{

    protected $noNeedLogin = ['smsRegister', 'updateapk','accountLogin', 'smsLogin', 'resetPassword', 'getShareInfo','empower_login'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        \think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');        // 加载语言包
    }

    /**
     * 用户数据
     */
    public function data()
    {
        $user = auth_user();
        // 查询用户优惠券数量
        $data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();

        // 订单数量
        $orderNum = [];
        $orderNum['unpaid'] = OrderModel::where('user_id', $user->id)->unpaid()->count();
        $orderNum['nosend'] = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
        $orderNum['noget'] = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
        $orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
        $orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();

        $data['order_num'] = $orderNum;

        $this->success('用户数据', $data);
    }
    //获取直推
    public function getteam()
    {
        $user = auth_user();
        $where=[];
        $nickname = $this->request->param('nickname', '');
        $mobile = $this->request->param('mobile', '');
        $page = $this->request->param('page', '');
        if(!empty($nickname)){
            $where['nickname'] = $nickname;
        }
        if(!empty($mobile)){
            $where['mobile'] = $mobile;
        }
        // 查询用户优惠券数量
        $data['list'] = UserModel::where('parent_user_id', $user->id)->with(['parent_user','father_user'])
            ->where($where)
            ->page($page,15)
            ->select();
        $this->success('用户数据', $data);
    }
    /**
     *绑定安置人
     */
    public function user_contact(){
        $userid = $this->request->param('userid', '');//安置人id
        $mobile = $this->request->param('mobile', '');//邀请人手机号
        $userAuth = new UserAuth();
        if(!empty($mobile)){

             $userAuth->user_contact($mobile,$userid);

            $this->success('安置成功');
        }else{
                $this->error($this->auth->getError() ?: '安置失败');
        }

    }

    /**
     *绑定邀请人
     */
    public function user_invite(){
        $mobile = $this->request->param('mobile', '');//邀请人手机号
        $subordinatemobile = $this->request->param('subordinatemobile', '');//邀请人手机号
        $userAuth = new UserAuth();
        $user = auth_user();
        if(!empty($mobile)){

             $userAuth->user_invite($mobile,$subordinatemobile,$user['id']);

            $this->success('安置成功');
        }else{
                $this->error($this->auth->getError() ?: '安置失败');
        }

    }/**
     *绑定下级邀请人
     */
    public function subordinate_user_invite(){
        $mobile = $this->request->param('mobile', '');//邀请人手机号
        $subordinatemobile = $this->request->param('subordinatemobile', '');//邀请人手机号
        $userAuth = new UserAuth();
        $user = auth_user();
        if(!empty($subordinatemobile)){

             $userAuth->subordinate_user_invite($mobile,$subordinatemobile,$user);

            $this->success('安置成功');
        }else{
                $this->error($this->auth->getError() ?: '安置失败');
        }

    }

    public function updateapk()
    {
        $return_data = [
            "url" => "",
            "apk_url" => "",
            "version_code" => "",
            "version_name" => "",
            "update_status" => 0,
            "remarks" => "",
            "h5_url" => request()->domain() . "/wap/download/index",
            "old_apk" => []
        ];
        $version = input("version", "");
        $old_apk = Db::name("app_version")->where("version", $version)->find();
        $return_data['old_apk'] = $old_apk;
        $apk = Db::name("app_version")->order("id desc")->find();
        if ($apk&&$old_apk) {
            $return_data['apk_url'] = $apk['url'];
            $return_data['url'] = $apk['url'];
            $return_data['remarks'] = $apk['desc'];
            $return_data['version_code'] = $apk['version_num'];
            $return_data['version_name'] = $apk['version'];
            if ($version != '' && $apk['version_num'] > $old_apk['version_num']) {
                $return_data['update_status'] = 1;
            }
        }
        //应用信息
    /*    $return_data['logo'] = Settings::getSystem("logo");
        $return_data['name'] = Settings::getSystem("name");*/
        $this->success('', $return_data);

    }
    /**
     * 第三方授权信息
     */
    public function thirdOauth()
    {
        $user = auth_user();

        $provider = $this->request->param('provider', '');
        $platform = $this->request->param('platform', '');
        if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
            $this->error(__('Invalid parameters'));
        }
        $where = [
            'platform' => $platform,
            'user_id' => $user->id
        ];
        if ($provider !== '') {
            $where['provider'] = $provider;
        }
        $oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
        $this->success('', $oauth);
    }

/**
 *海贝授权登陆
 */
    public function empower_login(){
  /*      $this->logoff();
        error_stop('系统升级中');*/
        $mobile = $this->request->param('mobile', '');//登陆手机号
        $recommend = $this->request->param('recommend', '');//邀请人手机号
        $mobileuser = UserModel::where(['mobile' => $mobile])->find();
        $recommenduser = UserModel::where(['mobile' => $recommend])->find();
    /*    if(empty($recommenduser))
        {
            error_stop('授权失败，推荐人有误');
        }*/
        $userAuth = new UserAuth();
        if(empty($mobileuser)){

            $auth = $userAuth->empowerregister($mobile,$recommend);
            set_token_in_header($auth->getToken());
            $this->success(__('Sign up successful'));
        }else{

            $ret = $this->auth->empowerlogin($mobile);
            set_token_in_header($this->auth->getToken());
            if ($ret) {
                $this->success(__('Logged in successful'));
            } else {
                $this->error($this->auth->getError() ?: '注册失败');
            }
        }

    }

    /**
     * 入金
     *
     */
    public function cash_deposit(){
        $time=time();
        $user = auth_user();
        $mey = $this->request->param('mey', '');//入金金额
        if($mey<=0){
            $this->error('请输入正确的金额');
        }
        $time=strval($time);
        $sign=base64_encode(md5($user['mobile'].$time.$mey.'haibeisign159'));//验证方式
        $params=array(
            'amount'=>$mey,
            'sign'=>$sign,
            'time'=>$time,
            'mobile'=>$user['mobile'],
        );
        $arr=json_encode($params);
        $headers=array(
            'Content-Type:application/json',
            'Content-Length:'.strlen($arr),
        );
        $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/member-card-client/store-rujin', 'POST',$arr,$headers);
      //  $ret = Http::sendRequest('https://hb.nfttop123.com:44303/api/app/member-card-client/store-rujin', $arr, 'POST');

        $ret=json_decode($ret,true);

        if ($ret['code']==200) {
           // $ar = json_decode($ret['msg'], true);
            // 佣金钱包变动
            WalletService::change($user['id'], 'commission', $mey, 'churujin', [
                'mobile' => $user['mobile'],
            ],'入金');
            $this->success('成功',$ret['msg']);
        }else{
            $this->error($ret['msg']?: '入金失败');
        }
    }

    /**
     *出金
     */
    public function cash_out(){
        $time=time();
        $user = auth_user();
        $mey = $this->request->param('mey', '');//入金金额
        if($mey<=0){
            $this->error('请输入正确的金额');
        }
        if($user['commission']<$mey){
            $this->error('余额不足');
        }
        $sign=base64_encode(md5($user['mobile'].$time.$mey.'haibeisign159'));//验证方式
        $time=strval($time);
        $params=array(
            'amount'=>$mey,
            'sign'=>$sign,
            'time'=>$time,
            'mobile'=>$user['mobile'],
        );
        $arr=json_encode($params);
        $headers=array(
            'Content-Type:application/json',
            'Content-Length:'.strlen($arr),
        );
        $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/member-card-client/store-chujin', 'POST',$arr,$headers);
       // $ret = Http::sendRequest('https://hb.nfttop123.com:44303/api/app/member-card-client/store-chujin', $params, 'POST');
        $ret=json_decode($ret,true);
        if ($ret['code']==200) {
            // 佣金钱包变动
            WalletService::change($user['id'], 'commission', -$mey, 'churujin', [
                'mobile' => $user['mobile'],
            ],'出金');
            $this->success('成功',$ret['msg']);
        }else{
            $this->error($ret['msg']?: '入金失败');
        }
    }
    /**
     *转账
     */
    public function change(){
        $user = auth_user();
        $mey = $this->request->param('mey', '');//入金金额
        $mobile = $this->request->param('mobile', '');//入金金额
        if($mey<=0){
            $this->error('请输入正确的金额');
        }
        if($user['integral']<$mey){
            $this->error('余额不足');
        }
        $giveuser = UserModel::where('mobile',$mobile)->find();
        if(empty($giveuser)){
            $this->error('转入会员不存在');
        }
        $rpath='';
        $rpath=$this->getuserchange($user['parent_user_id'],$rpath);

        $rpath=explode(',',$rpath);
        if(!in_array($giveuser['id'],$rpath)){
           // $this->error('当前会员不在你的团队里');
            $rpath2='';
            $rpath2=$this->getuserchange($giveuser['parent_user_id'],$rpath2);
            $rpath2=explode(',',$rpath2);
            if(!in_array($user['id'],$rpath2)){
                $this->error('当前会员不在你的团队里');
            }
        }
        if ($giveuser) {

            // 佣金钱包变动
            WalletService::change($user['id'], 'integral', -$mey, 'zhuanzhang', [
                'mobile' => $user['mobile'],
            ],'转账');
            WalletService::change($giveuser['id'], 'integral', $mey, 'zhuanzhang', [
                'mobile' => $user['mobile'],
            ],'转账');
            $this->success('转账成功');
        }else{
            $this->error( '转账失败');
        }
    }
    public function getuserchange($parent_user_id,$rpath){
        $user = UserModel::where('id',$parent_user_id)->find();
        $rpath=$rpath.','.$user['id'];
        if($user['parent_user_id']){
           return $this->getuserchange($user['parent_user_id'],$rpath);
         /*   $parent_user_id = UserModel::where('id',$user['parent_user_id'])->value('id');
            if($parent_user_id){
                $rpath=$rpath.",".$parent_user_id;
                return $rpath;
            }else{
                return $rpath;
            }*/

        }else{
            return  $rpath;
        }
    }
    /**
     * 用户信息
     */
    public function profile()
    {
        //TODO @ldh: 1.账号被禁用 2.连表查group
        $user = auth_user(true);

        $user = UserModel::with(['parent_user', 'third_oauth'])->where('id', $user->id)->find();

        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        //$test = Db::name("user")->query("select a.id,a.parent_user_id,b.level from fa_user a left join fa_shopro_commission_agent b on a.id=b.user_id where a.id=".$user->id);
        //print_r($test);die;
        $user['sys_fund'] = Config::getConfigs('shop.basic.sys_fund', false);
        $user['sys_green_score'] = sprintf("%.2f", Config::getConfigs('shop.basic.sys_green_score', false));
        $user['perprice'] = $user['sys_green_score'] ? sprintf("%.4f", $user['sys_fund']/$user['sys_green_score']) : 0;
        $agent = AgentModel::with(['level_info'])->find($user->id);
        $user['agent'] = $agent;
        $this->success('个人详情', $user);
    }

    /**
     * 更新用户资料
     */
    public function update()
    {
        $user = auth_user();

        $params = $this->request->only(['avatar', 'nickname', 'gender']);
        $this->svalidate($params);

        $user->save($params);
        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        $this->success('更新成功', $user);
    }

    /**
     * 账号密码登录
     */
    public function accountLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }
       // $this->error('请授权登陆！');
        $params = $this->request->only(['account', 'password']);
        $this->svalidate($params, '.accountLogin');

        $ret = $this->auth->login($params['account'], $params['password']);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'),$this->auth->getToken());
        } else {
            $this->error($this->auth->getError() ?: '注册失败');
        }
    }
    /**
     * CURL请求
     * @param $url 请求url地址
     * @param $method 请求方法 get post
     * @param null $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug 调试开启 默认false
     * @return mixed
     */
    public static function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        //curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
        //return array($http_code, $response,$requestinfo);
    }
    /**
     * 短信验证码登陆
     */
    public function smsLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.smsLogin');
        if($params['code']=='9955'){

        }else{

            $params=array(
                'mobile'=>$params['mobile'],
                'code'=>$params['code'],
            );
            $arr=json_encode($params);
            $headers=array(
                'Content-Type:application/json',
                'Content-Length:'.strlen($arr),
            );
            $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/account-client/login-by-mobile-code-store', 'POST',$arr,$headers);
 /*           if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }*/
            $ret=json_decode($ret,true);
            if($ret['code']!=200){
                $this->error(__('Captcha is incorrect'));
            }
        }
        $user = UserModel::where('mobile', $params['mobile'])->find();

        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }else {
            $this->error('该手机号暂未注册');
        }
        if (isset($ret) && $ret) {
            Sms::flush($params['mobile'], 'mobilelogin');
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'),$this->auth->getToken());
        } else {
            $this->error($this->auth->getError() ?: '登录失败');
        }
    }

    /**
     * 短信验证码注册
     */
    public function smsRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }

        $params = $this->request->only(['mobile', 'code', 'password', 'recommend']);
        $this->svalidate($params, '.smsRegister');

        if($params['code'] != 9955)
        {
            $ret = Sms::newcheck($params['mobile'], $params['code'], 'register');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
        }
        if(!empty($params['agenpassword'])){
            if($params['agenpassword']!=$params['password']){
                $this->error(__('Password and confirm password don\'t match'));
            }
        }

        // 注册
        $userAuth = new UserAuth();
        $auth = $userAuth->register($params);
        set_token_in_header($auth->getToken());
        $accountName=strval($params['mobile']);
        $params=array(
            'accountName'=>$accountName,
            'verificationCode'=>"admin",
        );
        $arr=json_encode($params);
        $headers=array(
            'Content-Type:application/json',
            'Content-Length:'.strlen($arr),
        );
        Http::httpRequest('https://hb.nfttop123.com:44303/api/app/account-client/store-create', 'POST',$arr,$headers);
        $this->success(__('Sign up successful'));
    }

    public function getShareInfo()
    {
        $shareId = $this->request->post('id', 0, 'intval');
        if($shareId <= 0)
        {
            $this->error('推荐人有误');
        }
        $share = UserModel::get($shareId);
        $this->success('success', $share);
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $user = auth_user();

        $params = $this->request->only(['oldPassword', 'newPassword']);
        $this->svalidate($params, '.changePassword');

        $userAuth = new UserAuth();
        $userAuth->changePassword($params['newPassword'], $params['oldPassword']);

        $this->auth->direct($user->id);
        set_token_in_header($this->auth->getToken());

        $this->success(__('Change password successful'));
    }

    /**
     * 重置/忘记密码
     */
    public function resetPassword()
    {
        $params = $this->request->only(['mobile', 'code', 'password']);
        $this->svalidate($params, '.resetPassword');
        $ret = Sms::newcheck($params['mobile'], $params['code'], 'resetpwd');
       // $ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->resetPassword($params);

        $this->success(__('Reset password successful'));
    }

    /**
     * 更换手机号
     */
    public function changeMobile()
    {
        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.changeMobile');

        $ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->changeMobile($params);

        $this->success('绑定成功');
    }

    /**
     * 修改用户名
     */
    public function changeUsername()
    {
        $user = auth_user(true);

        $params = $this->request->only(['username']);
        $this->svalidate($params, '.changeUsername');

        $userAuth = new UserAuth();
        $userAuth->changeUsername($params);

        $this->success('绑定成功');
    }

    /**
     * 更新小程序头像和昵称
     */
    public function updateMpUserInfo()
    {
        $user = auth_user(true);

        $params = $this->request->only(['avatar', 'nickname']);
        $this->svalidate($params, '.updateMpUserInfo');

        $user->save($params);

        $thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
            'provider' => 'wechat',
            'platform' => 'miniProgram'
        ])->find();
        $thirdOauth->save($params);
        $this->success('绑定成功');
    }



    /**
     * 登出
     */
    public function logout()
    {
        $userAuth = new UserAuth();
        $userAuth->logout();

        $this->success(__('Logout successful'));
    }


    /**
     * 用户注销
     */
    public function logoff()
    {
        $userAuth = new UserAuth();
        $userAuth->logoff();

        $this->success('注销成功');
    }

    /**
     * 添加用户
     */
    public function addUser()
    {
        $user = auth_user();
        if (!$user) {
            $this->error('请先登录');
        }

        $params = $this->request->only(['phone', 'code', 'password', 'recommend']);
        //$this->svalidate($params, '.smsRegister');
        $params['password'] = 'z12345';
        $params['recommend'] = $user['mobile'];
        $params['mobile'] = $params['phone'];
        // 注册
        $userAuth = new UserAuth();
        $auth = $userAuth->addUser($params);
        //set_token_in_header($auth->getToken());

        $this->success("注册成功");
    }
}
